import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  message,
  Divider, Modal,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import styles from '../UserManage.less';
import { powerBtnFunc } from "@/utils/utils";

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ deptModels, loading }) => ({
  deptModels,
  loading: loading.models.deptModels,
}))

@Form.create()
class DeptManage extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };


  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    //请求部门列表
    dispatch({
      type: 'deptModels/fetch',
      payload: {},
    });
    //请求用户列表
    dispatch({
      type: 'deptModels/getUserList',
      payload: {
        pageSize: 99999999,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;


    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
    };

    dispatch({
      type: 'deptModels/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'deptModels/fetch',
      payload: {},
    });
  };

  handleRemove = row => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: '确认',
      content: '确定删除该部门吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'deptModels/remove',
          payload: {
            key: row.deptNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('删除成功');
              this.setState({
                selectedRows: [],
              });
              dispatch({
                type: 'deptModels/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);

            }

          },
        });

      },
    });
  };
  handleDeptMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows, pagination } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        selectedRows.map((row) => {
          dispatch({
            type: 'deptModels/remove',
            payload: {
              key: row.deptNo,
            },
            callback: (res) => {
              if (res.code === 200) {
                message.success('删除成功');
                this.setState({
                  selectedRows: [],
                });
                dispatch({
                  type: 'deptModels/fetch',
                  payload: pagination,
                });
              } else {
                message.error(res.errMsg);

              }

            },
          });
        });
        break;
      case 'change':
        dispatch({
          type: 'deptModels/deptSort',
          payload: {
            firstSort: selectedRows[0].deptNo,
            secondSort: selectedRows[1].deptNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('交换成功');
              this.setState({
                selectedRows: [],
              });
              dispatch({
                type: 'deptModels/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);

            }

          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'deptModels/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    const { dispatch } = this.props;
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'deptModels/getDeptDesc',
          payload: { deptNo: record.deptNo },
        });
      }
    });
  };
  //新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'deptModels/add',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'deptModels/fetch',
        });
        this.handleModalVisible(false);
      },
    });

  };
  //修改请求
  handleUpdate = fields => {
    const { pagination } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'deptModels/update',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'deptModels/fetch',
          payload: pagination,
        });
        this.handleUpdateModalVisible(false, []);
      },
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="部门名称">
              {getFieldDecorator('deptName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { deptModels: { data, userList, deptDesc }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView } = this.state;
    const menu = (
      <Menu onClick={this.handleDeptMenuClick} selectedKeys={[]}>
        {
          powerBtnFunc('100011', <Menu.Item key="remove">删除</Menu.Item>)}
        {selectedRows.length === 2 ?
          (<Menu.Item key="change">交换</Menu.Item>) : ''
        }
      </Menu>
    );
    const columns = [
      {
        title: '部门编码',
        dataIndex: 'deptNo',
        key: 'deptNo',
      },

      {
        title: '部门名称',
        dataIndex: 'deptName',
        key: 'deptName',
      },

      {
        title: '负责人',
        dataIndex: 'adminName',
        key: 'adminName',
      },
      {
        title: '上级部门',
        dataIndex: 'parentNo',
        key: 'parentNo',
        render: val => <span>{data.data.map((item) => {
          return item.deptNo === val ? item.deptName : '';
        })}</span>,

      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: val => <span>{val === 1 ? '启用' : '停用'}</span>,
      },
      {
        title: '操作',
        key: 'dataIndex',
        render: (text, record) => (
          <Fragment>

            {
              powerBtnFunc('100008',
                [<a key={'btn'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
                  <Divider key={'divider'} type="vertical"/>],
              )
            }
            {
              powerBtnFunc('100009',
                [<a   key={'btn'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
                  <Divider  key={'divider'} type="vertical"/>],
              )}
            {
              powerBtnFunc('100011',
                <a  key={'btn'} onClick={() => this.handleRemove(record)}>删除</a>)}
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title="部门列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100007',
                  <Button key={'create'} icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                    添加部门
                  </Button>)
              }

            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowKey={'deptNo'}
              rowSelectHide={true}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {deptDesc
          ?
          <DescView handleLookDesc={this.handleLookDesc} selectedRows={deptDesc} lookDescView={lookDescView}/>
          :
          ''}
        <UpdateForm
          {...updateMethods}
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
          data={data}
          userList={userList}
        />

      </PageHeaderWrapper>
    );
  }
}

export default DeptManage;
